package com.zkthink.ceres.app.share.controller;

import cn.hutool.core.util.StrUtil;
import com.zkthink.base.R;
import com.zkthink.cache.repository.RedisRepositoryImpl;
import com.zkthink.ceres.applet.commission.service.AppletCommissionService;
import com.zkthink.ceres.common.utils.QcodeUtil;
import com.zkthink.ceres.common.utils.QrCodeVO;
import com.zkthink.ceres.common.utils.WxQrCodeUtil;
import com.zkthink.ceres.file.properties.FileServerProperties;
import com.zkthink.ceres.member.entity.Member;
import com.zkthink.ceres.member.service.MemberService;
import com.zkthink.context.BaseContextHandler;
import com.zkthink.utils.StrPool;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.util.ResourceUtils;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.nio.file.Paths;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;

import static com.zkthink.utils.DateUtils.DEFAULT_MONTH_FORMAT_SLASH;

/**
 * @ClassName ShareController
 * @Description: ShareController
 * @Author chenke
 * @Date 2021/11/15
 * @Version V1.0
 **/


@Slf4j
@Validated
@RestController
@RequestMapping("/share")
@Api(value = "分享服务", tags = "分享服务")
public class ShareController {

    @Autowired
    private MemberService memberService;
    @Autowired
    private RedisRepositoryImpl redisRepository;

    @Resource
    private FileServerProperties fileProperties;
    @Resource
    private AppletCommissionService appletCommissionService;

    @Value("${share.url}")
    private String url;
    @Value("${share.shopUrl}")
    private String shopUrl;

    @GetMapping("/getQRCode")
    @ApiOperation("获取二维码")
    public R getShare() {
        Long mid = BaseContextHandler.getUserId();
        String phone = null;
        if (mid != null) {
            Member byId = memberService.findById(mid);
            if (byId != null) {
                phone = (byId.getPhone() == null ? byId.getAccount() : byId.getPhone());
            }
        }

        String shareUrl = url + "?time=" + LocalDateTime.now() + "&phone=" + phone;

        QcodeUtil qrCodeUtil = new QcodeUtil();
        String path = null;
        String content = null;
        try {
            path = ResourceUtils.getURL("classpath:").getPath() + "logo/logo.png";
            System.out.println(path);
            System.out.println(ResourceUtils.getURL("classpath:").getPath());
            //String cotent=qrCodeUtil.createQRCode(String.valueOf(data.getId()),300,300,path);
            content = qrCodeUtil.createQRCode(String.valueOf(shareUrl), 300, 300);
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        Map<String, Object> map = new HashMap<>();
        map.put("url", shareUrl);
        map.put("QrCode", content);
        return R.success(map);
    }

    /**
     * 车惠龙分享获取二维码
     *
     * @return
     */
    @GetMapping("/shopGetQRCode")
    @ApiOperation("车惠龙分享获取二维码")
    public R shopGetQRCode() {
        Long mid = BaseContextHandler.getUserId();
        String phone = null;
        if (mid != null) {
            Member byId = memberService.findById(mid);
            if (byId != null) {
                phone = (byId.getPhone() == null ? byId.getAccount() : byId.getPhone());
            }
        }

        String shareUrl = url + "?time=" + LocalDateTime.now() + "&phone=" + phone;
        String fileName = UUID.randomUUID().toString() + StrPool.DOT + "png";
        //日期文件夹
        String relativePath = Paths.get(LocalDate.now().format(DateTimeFormatter.ofPattern(DEFAULT_MONTH_FORMAT_SLASH))).toString();
        // web服务器存放的绝对路径
        String absolutePath = Paths.get(fileProperties.getStoragePath(), relativePath).toString();
        QcodeUtil.getQRCode(shareUrl, Paths.get(absolutePath, fileName).toString());
        String url = new StringBuilder(fileProperties.getUriPrefix())
                .append(relativePath)
                .append(StrPool.SLASH)
                .append(fileName)
                .toString();

        //替换掉windows环境的\路径
        url = StrUtil.replace(url, "\\\\", StrPool.SLASH);
        url = StrUtil.replace(url, "\\", StrPool.SLASH);
        return R.success(url);
    }

    /**
     *车惠龙分享获取二维码获取链接
     *
     * @return
     */
    @GetMapping("/shopGetLink")
    @ApiOperation("车惠龙分享获取获取链接")
    public R getLink() {
        Long mid = BaseContextHandler.getUserId();
        String phone = null;
        if (mid != null) {
            Member byId = memberService.findById(mid);
            if (byId != null) {
                phone = (byId.getPhone() == null ? byId.getAccount() : byId.getPhone());
            }
        }
        String shareUrl = url + "?time=" + LocalDateTime.now() + "&phone=" + phone;
        return R.success(shareUrl);

    }

    @GetMapping("/getShareMyInfo")
    @ApiOperation("个人资料二维码")
    public R getShareMyInfo() throws IOException {
        QcodeUtil qrCodeUtil = new QcodeUtil();
        Long mid = BaseContextHandler.getUserId();
        Member member = memberService.findById(mid);
        QrCodeVO vo = new QrCodeVO();
        vo.setMid(member.getId());
        vo.setType(1);
        String content = qrCodeUtil.createQRCode(vo.toString(), 300, 300);
        return R.success(content);

    }

    @GetMapping("/getShareMyData")
    @ApiOperation("个人资料数据")
    public R<QrCodeVO> getShareMyData() {
//        QcodeUtil qrCodeUtil = new QcodeUtil();
        Long mid = BaseContextHandler.getUserId();
        Member member = memberService.findById(mid);
        QrCodeVO vo = new QrCodeVO();
        vo.setMid(member.getId());
        vo.setType(1);
//        String  content = qrCodeUtil.createQRCode(entity.toString(), 300, 300);
        return R.success(vo);

    }

    @GetMapping("/getShareUrl")
    @ApiOperation("获取Url")
    public R getShareUrl() {
        Long mid = BaseContextHandler.getUserId();
        String phone = null;
        if (mid != null) {
            Member byId = memberService.findById(mid);
            if (byId != null) {
                phone = (byId.getPhone() == null ? byId.getAccount() : byId.getPhone());
            }
        }

        String shareUrl = url + "?time=" + LocalDateTime.now() + "&phone=" + phone;
        Map<String, Object> map = new HashMap<>();
        map.put("url", shareUrl);
        return R.success(map);
    }


    @GetMapping("/getWMinQrCode")
    @ApiOperation("得到小程序二维码")
    public R getWMinQrCode() throws IOException {
        Long mid = BaseContextHandler.getUserId();
        Member member = memberService.findById(mid);
        String accessToken = redisRepository.get("accessToken");
        if (accessToken == null) {
            try {
                Map<String, String> accessToken1 = WxQrCodeUtil.getAccessToken();
                accessToken = accessToken1.get("accessToken");
                if (accessToken == null) {
                    return R.fail("参数错误");
                }
                long expiresIn = Long.valueOf(accessToken1.get("expiresIn")).longValue();
                redisRepository.setExpire("accessToken", accessToken, expiresIn);
            } catch (Exception e) {
                return R.fail("参数错误");
            }
        }
        String fileName = UUID.randomUUID().toString() + StrPool.DOT + "png";
        //日期文件夹
        String relativePath = Paths.get(LocalDate.now().format(DateTimeFormatter.ofPattern(DEFAULT_MONTH_FORMAT_SLASH))).toString();
        // web服务器存放的绝对路径
        String absolutePath = Paths.get(fileProperties.getStoragePath(), relativePath).toString();
        String scene = "phone=" + member.getAccount();
        String page = "pages/index/index";
        WxQrCodeUtil.getminiqrQr(scene, page, accessToken, Paths.get(absolutePath, fileName).toString());
        String url = new StringBuilder(fileProperties.getUriPrefix())
                .append(relativePath)
                .append(StrPool.SLASH)
                .append(fileName)
                .toString();

        //替换掉windows环境的\路径
        url = StrUtil.replace(url, "\\\\", StrPool.SLASH);
        url = StrUtil.replace(url, "\\", StrPool.SLASH);
        return R.success(url);

    }


    @GetMapping("/getQrPic")
    @ApiOperation("得到分享链接二维码图片链接")
    public R getQrPic() throws IOException {
        Long mid = BaseContextHandler.getUserId();
        String phone = null;
        if (mid != null) {
            Member byId = memberService.findById(mid);
            if (byId != null) {
                phone = (byId.getPhone() == null ? byId.getAccount() : byId.getPhone());
            }
        }

        String shareUrl = url + "?time=" + LocalDateTime.now() + "&phone=" + phone;
        String fileName = UUID.randomUUID().toString() + StrPool.DOT + "png";
        //日期文件夹
        String relativePath = Paths.get(LocalDate.now().format(DateTimeFormatter.ofPattern(DEFAULT_MONTH_FORMAT_SLASH))).toString();
        // web服务器存放的绝对路径
        String absolutePath = Paths.get(fileProperties.getStoragePath(), relativePath).toString();
        QcodeUtil.getQRCode(shareUrl, Paths.get(absolutePath, fileName).toString());
        String url = new StringBuilder(fileProperties.getUriPrefix())
                .append(relativePath)
                .append(StrPool.SLASH)
                .append(fileName)
                .toString();

        //替换掉windows环境的\路径
        url = StrUtil.replace(url, "\\\\", StrPool.SLASH);
        url = StrUtil.replace(url, "\\", StrPool.SLASH);
        return R.success(url);
    }


    @PostMapping("/getMyInfoPic")
    @ApiOperation("得到个人资料二维码图片链接")
    public R getMyInfoPic(@RequestBody QrCodeVO content) throws IOException {
        Long mid = BaseContextHandler.getUserId();
        String fileName = UUID.randomUUID().toString() + StrPool.DOT + "png";
        //日期文件夹
        String relativePath = Paths.get(LocalDate.now().format(DateTimeFormatter.ofPattern(DEFAULT_MONTH_FORMAT_SLASH))).toString();
        // web服务器存放的绝对路径
        String absolutePath = Paths.get(fileProperties.getStoragePath(), relativePath).toString();
        QcodeUtil.getQRCode(content.getContent(), Paths.get(absolutePath, fileName).toString());
        String url = new StringBuilder(fileProperties.getUriPrefix())
                .append(relativePath)
                .append(StrPool.SLASH)
                .append(fileName)
                .toString();

        //替换掉windows环境的\路径
        url = StrUtil.replace(url, "\\\\", StrPool.SLASH);
        url = StrUtil.replace(url, "\\", StrPool.SLASH);
        return R.success(url);
    }

    @GetMapping("/getShareMember")
    @ApiOperation("获取当前登录用户的推荐用户列表")
    public R getShareMember(){
        Map<String,Object> map = appletCommissionService.getShareMember();;
        return R.success(map);
    }


}
